package org.syx.edl.nio;

import org.syx.edl.ItemWriter;
import org.syx.edl.LineAggregator;

import java.io.*;
import java.util.List;

/**
 * @author:whh
 * @date: 2025-09-06 15:06
 * <p></p>
 */
public class FileLineWriter<T> implements ItemWriter<T> {


    private File file;
    private BufferedWriter writer;

    private String charset;

    private LineAggregator<T> lineAggregator;

    private boolean append;

    public FileLineWriter() {
    }

    public FileLineWriter(File file, String charset, boolean append,LineAggregator<T> lineAggregator) {
        this.file = file;
        this.charset = charset;
        this.append=append;
        this.lineAggregator = lineAggregator;
    }

    @Override
    public void open() throws Exception {
        this.writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,append),charset));
    }

    @Override
    public void write(List<T> items) throws Exception {
        for (T item : items) {
            writer.write(lineAggregator.aggregate(item));
            writer.newLine();
        }
        //write to file
        writer.flush();
    }

    @Override
    public void close() throws Exception {
        if(writer!=null){
            writer.close();
        }
    }
}
